package org.brisling.portal.queryService;

import java.io.UnsupportedEncodingException;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.brisling.authorize.shiro.SSOService;
import org.brisling.base.domain.BSListDomain;
import org.brisling.base.domain.ListDomain;
import org.brisling.base.domain.RetDomain;
import org.brisling.base.service.AbstractBaseQueryService;
import org.brisling.common.ConstSysParam;
import org.brisling.common.SysConfig;
import org.brisling.common.exception.SessionExpiredException;
import org.brisling.common.exception.UserameOrPasswordWrongException;
import org.brisling.common.util.DateUtil;
import org.brisling.common.util.JsonUtil;
import org.brisling.common.util.LongUtil;
import org.brisling.docManage.domain.Docdetail;
import org.brisling.docManage.domain.Doctype;
import org.brisling.docManage.queryService.QueryDocService;
import org.brisling.docManage.queryService.QueryDoctypeService;
import org.brisling.docManage.service.DocdetailService;
import org.brisling.duties.domain.DutiesComplain;
import org.brisling.duties.service.DutiesComplainService;
import org.brisling.honest.domain.HonestDomain;
import org.brisling.medical.domain.MedicalInpatient;
import org.brisling.medical.domain.MedicalOutpatient;
import org.brisling.medical.queryService.QueryInpatientService;
import org.brisling.medical.queryService.QueryOutpatientService;
import org.brisling.mobile.config.RSAConfig;
import org.brisling.satisfaction.domain.SatisfactionEvaluateMessage;
import org.brisling.satisfaction.domain.SatisfactionEvaluateSubject;
import org.brisling.satisfaction.queryService.QuerySatisfactionEvaluateMessageService;
import org.brisling.satisfaction.queryService.QuerySatisfactionEvaluateSubjectService;
import org.brisling.satisfaction.service.SatisEvaluateService;
import org.brisling.satisfaction.service.SatisfactionEvaluateMessageService;
import org.brisling.satisfaction.service.SatisfactionEvaluateResultService;
import org.brisling.sysman.domain.SysLob;
import org.brisling.sysman.domain.SysLogs;
import org.brisling.sysman.domain.UploadFiles;
import org.brisling.sysman.domain.UserPassword;
import org.brisling.sysman.domain.Users;
import org.brisling.sysman.queryService.QueryUploadService;
import org.brisling.sysman.queryService.QueryUserService;
import org.brisling.sysman.service.LobService;
import org.brisling.sysman.service.LogService;
import org.brisling.sysman.service.SecurityUserService;
import org.brisling.sysman.service.UploadService;
import org.brisling.workflow.service.WorkflowOperatorService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;

@RestController
public class QueryPortalService extends AbstractBaseQueryService<HonestDomain>{
	
	
	@Autowired
	private QueryDocService qryDocService;
	
	
	@Autowired
	private QueryUserService queryUserService;
	
	
	@Autowired
	private SecurityUserService securityUserService;
	
	
	@Autowired
	private UploadService uploadService;
	
	@Autowired
	private QueryUploadService qryUploadService;
	
	
	@Autowired
	private LobService lobService;	
	
	@Autowired
	private QueryDoctypeService qryDoctypeService;
	
	
	//住院信息查询
	@Autowired
	private QueryInpatientService qryInpatientService;
	
	
	//门诊信息查询
	@Autowired
	private QueryOutpatientService qryOutpatientService;
	
	
	//满意度问卷问题查询
	@Autowired
	private QuerySatisfactionEvaluateSubjectService qrySatiSubjectService;
	
	@Autowired
	private SatisfactionEvaluateMessageService semService;
	
	@Autowired
	private SatisfactionEvaluateResultService serService;
	
	//已经评价的患者信息查询
	@Autowired
	private QuerySatisfactionEvaluateMessageService qrySemService;
	
	//文档点击计数器
	@Autowired
	private DocdetailService docdetailService;
	
	
	@PersistenceContext(unitName=ConstSysParam.SUBSYSTEM_SYSMAN)
	@Autowired
	protected void setEntityManager(EntityManager entityManager){
		this.entityManager = entityManager;		
	}
	
	
	@RequestMapping("/{modulename}/login")
	@ResponseBody
	public ModelAndView moduleLogin(
						@PathVariable("modulename") String modulename
						) throws UserameOrPasswordWrongException, SessionExpiredException{
		if(modulename==null){
			modulename = "risk";
		}	
		
		return new ModelAndView("/"+modulename );
		
	}
	
	/**
	 * 获取站点页面视图
	 * @param sitename	站点名称
	 * @param code		页面名称
	 * @return
	 */
	@RequestMapping("/{sitename}/getPage")
	public ModelAndView getSitePage(
			@PathVariable("sitename") String sitename,
			@RequestParam(value="code",required=false) String code){
		
		
		String _page =code==null?"main":code;
		String _sitePath = String.format("/%1$s/%2$s", sitename,_page);
		return new ModelAndView(_sitePath);
	}
	/**
	 * 获取门户文档内容视图
	 * @return
	 */
	@RequestMapping("/contentPage")
	public ModelAndView getContentPage(){
		String orgcode = SysConfig.getConfig("orgcode");
		return new ModelAndView("/"+orgcode+"/portal/content-page");
	}
	
	/**
	 * 获取住院满意度评价内容视图
	 * @return
	 */
	@RequestMapping("/questionary")
	public ModelAndView getQuestionary(){		
		
		return new ModelAndView("/questionary");
	}
	
	
	/**
	 * 获取住院满意度评价内容视图
	 * @return
	 */
	@RequestMapping("/getPage")
	public ModelAndView getPage(@RequestParam(value="pageCode",required=false)String pageCode){		
		
		if(pageCode!=null){
			return new ModelAndView("/"+pageCode);
		}
		return null;
	}
	
	/**
	 * 获取预览文档页面
	 * @return
	 */
	@RequestMapping("/preview")
	public ModelAndView preview(){		
		
		return new ModelAndView("/preView");
	}
	
	/**
	 * 获取站点文档内容页视图
	 * @param sitename
	 * @return
	 */
	@RequestMapping("/{sitename}/contentPage")
	public ModelAndView getSiteContentPage(@PathVariable("sitename") String sitename){
		
		return new ModelAndView("/"+sitename+"/content-page");
	}
	
	/**
	 * 获取门户文档列表视图
	 * @return
	 */
	@RequestMapping("/getContentList")
	public ModelAndView getContentList(){
		String orgcode = SysConfig.getConfig("orgcode");
		return new ModelAndView("/"+orgcode+"/portal/content-list");
	}
	
	/**
	 * 获取站点文档列表视图
	 * @param sitename
	 * @return
	 */
	@RequestMapping("/{sitename}/getContentList")
	public ModelAndView getSiteContentList(@PathVariable("sitename") String sitename){
		
		return new ModelAndView("/"+sitename+"/content-list");
	}
	
	
	/**
	 * 获取首页文档分类列表
	 * @param body
	 * @return
	 */
	@RequestMapping("/getTypeListDomain")
	public ListDomain<Docdetail> getTypeListDomain(@RequestBody(required=false) String body){		
		
		return qryDocService.getTypeListDomain(body);
	}
	
	/**
	 * 获取首页文档分类列表
	 * @param body
	 * @return
	 */
	@RequestMapping("/getTypeBSListDomain")
	public BSListDomain<Docdetail> getTypeBSListDomain(@RequestBody(required=false) String body){		
		
		return qryDocService.getTypeBSListDomain(body);
	}
	

	/**
	 * 获取首页文档分类列表
	 * @param body
	 * @return
	 */
	@RequestMapping("/getTypeListDomainConcat")
	public ListDomain<Docdetail> getTypeListDomainConcat(@RequestBody(required=false) String body){		
		
		return qryDocService.getTypeListDomainConcat(body);
	}
	
	/**
	 * 获取首页图片分页列表
	 * @param body
	 * @return
	 */
	@RequestMapping("/getPicListDomain")
	public List<UploadFiles> getPicListDomain(@RequestBody(required=false) String body){
		return qryDocService.getPicListDomain(body);
	}
	
	/**
	 * 获取图片内容
	 * @param id	图片id
	 * @param request
	 * @param respones
	 */
	@RequestMapping("/getImage")
	public void getImage(@RequestParam(value="id",required=false)Long id,HttpServletRequest request,HttpServletResponse respones){
		
		uploadService.getImage(id, request, respones);
		
	}
	
	/**
	 * 获取图片内容
	 * @param id	图片id
	 * @param request
	 * @param respones
	 */
	@RequestMapping("/getFile")
	public void getFile(@RequestParam(value="id",required=false)Long id,HttpServletRequest request,HttpServletResponse respones){
		
		uploadService.downloadFile(id, request, respones);
		
	}
	
	
	
	/**
	 * 验证登录
	 * @param userid
	 * @param pwd
	 * @return
	 */
	@RequestMapping("/authenticate")
	public RetDomain authen(@RequestParam(value="userid",required=false) String userid,
			@RequestParam(value="pwd",required=false) String pwd){
		UserPassword up= queryUserService.getUserPassword(userid);
		if(up!=null && up.getYhid()!=null){
			userid = up.getYhid().trim();
		}
		
		RetDomain rd = null;
		
		if(SysConfig.getUsingSSO()){
			rd =SSOService.verifyPassword(userid, pwd,up.getYhmm());
		}else{
			Users u = securityUserService.getOne(LongUtil.getLongValue(userid, null));
			if(u!=null && u.getId()!=null){
				rd =SSOService.verifyLocalMD5(u, pwd,up.getYhmm());
			}
		}
		if(rd!=null && rd.getStatus()!=null){
			Users u = queryUserService.getOne(LongUtil.getLongValue(userid, null));
			if(u!=null){				
				String _msg = String.format("{\"name\":\"%1$s\",\"deptId\":\"%2$d\","
										  + "\"deptName\":\"%3$s\",\"yhid\":\"%4$d\"}", 
										  u.getName(),u.getDeptid(),u.getDeptName(),u.getId());
				
				System.out.println("_msg: " + _msg);
				rd.setMsg(_msg);
			}			
			return rd;
		}else{
			rd = new RetDomain();
			rd.setErrorMsg("error");
			return rd; 
		}
	}
	
	/**
	 * 获取医院名称
	 * @return
	 */
	@RequestMapping("/getHostpitalName")
	public RetDomain getHostpitalName(){
		RetDomain domain = new RetDomain();
		
		domain.setSuccessMsg(SysConfig.getHospital_name());
		return domain;		
	}
	
	/**
	 * 获取配置信息
	 * @param configName
	 * @return
	 */
	@RequestMapping("/getConfig")
	public RetDomain getConfig(@RequestParam(value="configName",required=false) String configName){
		RetDomain domain = new RetDomain();
		
		domain.setSuccessMsg(SysConfig.getConfig(configName));
		return domain;		
	}
	
	/**
	 * 查询单条文档内容
	 * @param docid
	 * @return
	 */
	@RequestMapping("/getContentOne")
	public Docdetail getContentOne(@RequestParam(value="docid",required=false) Long docid){
		
		Docdetail detail = null;
		if(docid!=null){
			detail = qryDocService.getOne(docid);
			if((detail!=null) && (detail.getLobid()!=null)){
				String _lobid = detail.getLobid().trim();
				if(_lobid.length()>0){
					Long lid = LongUtil.getLongValue(_lobid, null);
					if(lid!=null){
						
						SysLob sl = lobService.getOne(lid);
						
						if(sl!=null){
							String contents = sl.getLob_contents();
							if(contents!=null){
								contents = StringUtils.normalizeSpace(contents);
							}
							detail.setLob_contents(contents);
						}
					}
				}
			}
		}
		return detail;
	}
	
	/**
	 * 获取附件预览信息
	 * @param docid
	 * @return
	 */
	@RequestMapping("/getContentArchive")
	public RetDomain getContentArchive(@RequestParam(value="docid",required=false) Long docid){
		RetDomain domain = RetDomain.successDomain("success");
		if(docid!=null){
			Docdetail detail = null;
			detail = qryDocService.getOne(docid);
			Map<String,String> map = new HashMap<String,String>();
			map.put("bizno_in", String.valueOf(detail.getId()));
			
			map.put("bizcode", detail.getTypeCode());
			List<UploadFiles>  lists =qryUploadService.getList(map);
			
			List<Map<String,String>> retLists = new ArrayList<Map<String,String>>();
			for(UploadFiles u:lists){
				Map<String,String> pMap = new HashMap<String,String>();
				pMap = uploadService.previewFile(u.getId());
				
				retLists.add(pMap);
			}
			
			domain.setRows(retLists);
		}else{
			domain = RetDomain.errorDomain("为查找到附件信息");
		}
		return domain;
	}
	
		
	
	/**
	 * 获取文档列表
	 * @param body
	 * @return
	 */
	@RequestMapping("/getDoctypeListDomain")
	public ListDomain<Doctype> getDoctypeListDomain(@RequestBody(required=false) String body){
		return qryDoctypeService.getListDomain(body);
	}
	
	
	/**
	 * 获取文档名称列表（长度截断）
	 * @param body
	 * @return
	 */
	@RequestMapping("/getDoctypeSubListDomain")
	public ListDomain<Doctype> getDoctypeSubListDomain(@RequestParam(value="bizcode",required=false) String bizcode){
		return qryDoctypeService.getSubListDomain(bizcode);
	}
	
	
	
	/**
	 * 获取软件下载页面视图
	 * @param sitename	站点名称
	 * @param code		页面名称
	 * @return
	 */
	@RequestMapping("/getFileListPage")
	public ModelAndView getFileListPage(
			){	
		
		return uploadService.getExternalPage("fileList");
	}
	/**
	 * 获取外部软件清单
	 * @param body
	 * @return
	 */
	@RequestMapping("/getExternalFileList")
	public List<Map<String,String>> getExternalFileList(){
		return uploadService.getExternalFileList();
		
	}
	
	/**
	 * 下载外部软件
	 * @param body
	 * @return
	 */
	@RequestMapping("/getExternalFile")
	public void getExternalFile(@RequestParam(required=false) String fileName,HttpServletRequest request,HttpServletResponse response){
		uploadService.getExternalFile(fileName,request,response);		
	}
	
	/**
	 * 查询住院患者信息
	 * @param fileName
	 */
	@RequestMapping("/getInpateintInfo")
	public MedicalInpatient getInpateintInfo(@RequestParam(required=false) String patient_no){
		List<MedicalInpatient> inpatientLists = qryInpatientService.getListByPatientNo(patient_no);
		if (inpatientLists != null && inpatientLists.size() >= 1) {
			MedicalInpatient e = inpatientLists.get(0);
			if (isEvaluated(patient_no, e.getPatient_id())) {
				return null;
			}
			return e;
		}
		return null;
	}
	
	//判断此住院号或者门诊号是否已经评价(patient_no, patient_id为病人的门诊号或者住院号)
	private Boolean isEvaluated(String patient_no, String patient_id) {
		if (patient_no != null && patient_id != null) {
			String sql = "SELECT * FROM V_SATIS_EVALUATE_MESSAGE WHERE patient_code = to_char(%1$s) AND patient_id = to_char(%2$s)";
			sql = String.format(sql, patient_no, patient_id);
			List<SatisfactionEvaluateMessage> lists = qrySemService.getAllList(sql);
			if (lists.size() >= 1) {
				return true;
			}
			return false;
		}
		return true;
	}
	
	
	/**
	 * 查询门诊患者信息
	 * @param fileName
	 */
	@RequestMapping("/getOutpateintInfo")
	public MedicalOutpatient getOutpateintInfo(@RequestParam(required=false) String patient_no){
		List<MedicalOutpatient> outpatientLists = qryOutpatientService.getListByPatientNo(patient_no);
		if (outpatientLists != null && outpatientLists.size() >= 1) {
			MedicalOutpatient e = outpatientLists.get(0);
			if (isEvaluated(patient_no, e.getOutpatient_number())) {
				return null;
			}
			return e;
		}
		return null;
	}
	
	/**
	 * 
	 * @param 
	 * @return 门诊问卷问题
	 */
	
	@RequestMapping("/getOutpatientQueDomain")
	public ListDomain<SatisfactionEvaluateSubject> getOutpatientQueListDomain(){	
		return qrySatiSubjectService.getListDomain("1");
	}
	
	/**
	 * 
	 * @param 
	 * @return 住院问卷问题
	 */
	
	@RequestMapping("/getInpatientQueListDomain")
	public ListDomain<SatisfactionEvaluateSubject> getInpatientQueListDomain(){
		return qrySatiSubjectService.getListDomain("2");
	}
	
	
	/**
	 * 保存自助终端满意度评价
	 * @param body
	 */
	@RequestMapping("/saveEvaluateResult")
	public RetDomain saveEvaluateResult(@RequestBody(required=false) String body) {
		
		TmpResult obj = JsonUtil.bodyToObj(body, TmpResult.class);	
		String _datalist = null;
		String _type = null;
		String _userid = null;
		
		if(obj!=null){
			_datalist = obj.getDataList();
			_type = obj.getType();
			_userid = obj.getUserid();			
		}
		
		
		if(_type!=null){
			_type = _type.trim();
			if(_type.compareTo("1")==0){
				//门诊
				List<MedicalOutpatient> outpatientLists = qryOutpatientService.getListByPatientNo(_userid);
				SatisfactionEvaluateMessage e = semService.saveOutpatientMessage(outpatientLists.get(0));
				if (e != null) {
					serService.saveEvaluateResult(_datalist, String.valueOf(e.getId()));
					return RetDomain.successDomain("success");
				}
				outpatientLists.clear();
				return RetDomain.errorDomain("error");
			}
			else{
				//住院
				List<MedicalInpatient> inpatientLists = qryInpatientService.getListByPatientNo(_userid);
				SatisfactionEvaluateMessage e = semService.saveInpatientMessage(inpatientLists.get(0));
				if (e != null) {
					serService.saveEvaluateResult(_datalist, String.valueOf(e.getId()));
					return RetDomain.successDomain("success");
				}
				inpatientLists.clear();
				return RetDomain.errorDomain("error");
			}
		}		
		return RetDomain.errorDomain("error");
	}

	
	/**
	 * 查询附件列表
	 * @param body
	 * @return
	 */
	@RequestMapping("/getInitListDomain")
	public ListDomain<UploadFiles> getInitListDomain(
			@RequestBody(required=false) String body){
		
		return qryUploadService.getInitListDomain(body);
		
		
	}
	
	
	
	
	@Autowired
	private SatisEvaluateService evaluateService;
	/**
	 * 执行窗口评价
	 * @param body
	 * @return
	 */
	@RequestMapping("/evaluate")
	@ResponseBody
	public RetDomain evaluate(@RequestParam(value="userid",required=false) String userid,
			@RequestParam(value="username",required=false) String username,
			@RequestParam(value="patientno",required=false) String patientno,
			@RequestParam(value="patientname",required=false) String patientname,
			@RequestParam(value="outpatient_number",required=false) String outpatient_number,
			@RequestParam(value="type",required=false) Integer type,
			@RequestParam(value="result",required=false) Integer result,
			@RequestBody(required=false) String body){
		
		
		String gb2312Username = "";
		String gbkUsername = "";
//		String gb2312Username = "";
		
		if(username!=null){
			try {
				gb2312Username = new String(username.getBytes("UTF-8"), "GB2312");
			} catch (UnsupportedEncodingException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			
			try {
				gb2312Username = new String(username.getBytes("GB2312"), "UTF-8");
			} catch (UnsupportedEncodingException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			
			try {
				gbkUsername = new String(username.getBytes("UTF-8"), "GBK");
			} catch (UnsupportedEncodingException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			
			try {
				gbkUsername = new String(username.getBytes("GBK"), "UTF-8");
			} catch (UnsupportedEncodingException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		RetDomain domain = evaluateService.remoteSave(userid,username,patientno,patientname,outpatient_number,type, result, body);
			
		return domain;		
	}
	
	
	/**
	 * 获取加密公钥
	 * @return
	 */
	@RequestMapping("/getPublicKey")
	public PublicKey getPublicKey(){
		
		String keycode = RSAConfig.getInitKey();
		Map<PublicKey, PrivateKey> rsaMap = RSAConfig.getVerifyKeyPaire(keycode);
		return RSAConfig.getPublicKey(rsaMap);
	}
	
	/**
	 * 文档点击计数器
	 * @param id
	 * @return
	 */
	@RequestMapping("/clickCnt")
	public RetDomain clickCnt(@RequestParam(value="id",required=false) Long id){
		
		return docdetailService.updateCnt(id);
	}
	
	
	
	@Autowired
	private LogService logService;
	/**
	 * 日志记录
	 * @param log
	 */
	public void logRecord(SysLogs log){
		logService.save(log);
	}
	
	@Autowired
	private DutiesComplainService complainService;
	
	//获取投诉弹窗页面
	@RequestMapping("/getComplainPopPage")
	public ModelAndView getComplainPopPage(){
		String _page = "/complainEditDlg";		
		return new ModelAndView(_page);
	}
	
	/**
	 * 保存投诉记录
	 * @param id
	 */
	@RequestMapping("/complainSave")
	public DutiesComplain save(@RequestBody String body){
		return complainService.save(body);
	}
	
	
	@Autowired
	private WorkflowOperatorService workflowOperatorService;
	/**
	 * 流程用户授权
	 * @param flowInstId
	 * @param userid
	 * @return
	 */
	@RequestMapping("/flowsign")
	public int flowsign(@RequestParam(value="flowInstId",required=false)String flowInstId,
    		@RequestParam(value="userid",required=false)String userid){
		return workflowOperatorService.flowsign(flowInstId, userid);
	}
	
	/**
	 * 获取指定月份最后一天
	 * @param yearMonth
	 * @param year
	 * @param month
	 * @return 返回"yyyy-MM-dd"格式指定月份最后一天的日期值
	 */
	@RequestMapping("/getMonthLastDay")
	public String getMonthLastDay(@RequestParam(value="yearMonth",required=false) String yearMonth,
			@RequestParam(value="year",required=false) String year,
			@RequestParam(value="month",required=false) String month){
		
		int _year = 0;
		int _month = 0;
		if(yearMonth!=null){
			year = yearMonth.substring(0,4);
			month = yearMonth.substring(5,yearMonth.length());
			
		}
		
		_year = Integer.parseInt(year);
		_month = Integer.parseInt(month);
		
		
		if(_year != 0 && _month != 0){
			String[] ret = DateUtil.getMonthDay(_year, _month);
			if(ret!=null && ret.length>=2)
				return ret[1];
		}
		
		return null;
	}
}
